package com.hs.room.repository

import android.content.Context
import com.hs.common.UserInitInfo
import com.hs.common.dto.SysUserDto
import com.hs.common.repository.IUserRepository
import com.hs.framework.utils.DateUtils
import com.hs.framework.utils.HashUtils
import com.hs.room.AppDatabase
import com.hs.room.mapper.UserMapper
import com.hs.room.model.sys.SysUser
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import java.time.LocalDateTime
import javax.inject.Inject

/**
 *   写多这一层 是方便扩展 ：
 *
 */

class UserRoomRepository @Inject constructor(
    @ApplicationContext var context: Context,
    val database: AppDatabase
) : IUserRepository {


    /**
     * 查询系统的账号
     */
    private suspend fun selectBySysTemNo(sysTemNo: String): SysUser {
        return database.userDao().selectBySysTemNo(sysTemNo)
    }

    override suspend fun initUser(sysTemNo: String) {
        selectBySysTemNo(sysTemNo)?.let { adminUser ->
            // 这里可以对非空的adminUser进行后续操作
            println("init user 成功： 这里可以对非空的adminUser进行后续操作")
        } ?: run {
            val dept = UserInitInfo.deptMap.entries.first();
            val role = UserInitInfo.roleMap.entries.first();
            val sysUser = SysUser(
                userName = UserInitInfo.userName,
                account = UserInitInfo.account,
                password = HashUtils.sha1(UserInitInfo.password),
                sysTemNo = sysTemNo,
                createBy = "system",
                createTime = DateUtils.formatLocalDateTime(LocalDateTime.now()),
                createTimestamp = System.currentTimeMillis(),
                deptName = dept.key,
                deptCode = dept.value,
                roleName = role.key,
                roleCode = role.value,
                screenshot = "",
                loginType = 0
            )
            println("${sysUser}")
            database.userDao().insertUser(sysUser)
        }
    }

    /**
     * 插入用户
     */
    override suspend fun insertUser(user: SysUserDto) {
        database.userDao().insertUser(UserMapper.INSTANCE.userDtoToUser(user))
    }

    override suspend fun updateUser(user: SysUserDto): Int {
        return database.userDao().updateUser(UserMapper.INSTANCE.userDtoToUser(user))
    }


    /**
     * 查询数据
     */
    override fun getAllUsers(): Flow<List<SysUserDto>> {
        return flow {
            val userFlow = database.userDao().getAllUsers()
                .filter { it.isNotEmpty() }
                .map { UserMapper.INSTANCE.usersToUserDTOs(it) }
            emitAll(userFlow)
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching user data: $e")
        }
    }

    /***
     *  通过账号查找用户
     */
    override suspend fun selectByAccount(account: String): SysUserDto? {
        val user = database.userDao().selectByAccount(account)
//        if (user != null){
//           val  sysUserDto: SysUserDto = UserMapper.INSTANCE.userToUserDTO(user)
////            println("selectByAccount ${sysUserDto}")
//        }
        return user?.let { UserMapper.INSTANCE.userToUserDTO(it) } ?: null

    }

    override suspend fun selectByFingerId(templateId: Int): SysUserDto? {
        val user = database.userDao().selectByFingerId(templateId)
        return user?.let { UserMapper.INSTANCE.userToUserDTO(it) } ?: null
    }

    override suspend fun getMaxFeatureId(): Int {
        return database.userDao().getMaxFeatureId() ?: 1
    }


}